﻿﻿using DeviceCommons.DataHandling;
using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Enums;
using DeviceCommons.DeviceMessages.Models.V1;
using DeviceCommons.Validation;

namespace DeviceCommons.DeviceMessages.Serialization.V1.Parsers
{
    public class DeviceMessageInfoReadingStateParser : AbstractMessageParser<IDeviceMessageInfoReadingState>, IDeviceMessageInfoReadingStateParser
    {
        public DeviceMessageInfoReadingStateParser() : base(new DeviceMessageInfoReadingState())
        {
        }

        public override IDeviceMessageInfoReadingState Parser(ReadOnlySpan<byte> bytes)
        {
            if (bytes.Length < 2)
                throw new DeviceMessageValidationException(
                    ValidationErrorType.InsufficientDataLength,
                    "状态解析数据不足，至少需要2字节的状态头部",
                    nameof(bytes),
                    "至少 2 字节 (SID + ValueType)",
                    $"{bytes.Length} 字节");

            byte sid = bytes[0];
            StateValueTypeEnum valueType = (StateValueTypeEnum)bytes[1];
            int dataStartIndex = 2;
            int valueLength;

            if (valueType == StateValueTypeEnum.String || valueType == StateValueTypeEnum.Binary)
            {
                int lengthFieldSize = valueType == StateValueTypeEnum.String ? 1 : 2;
                if (bytes.Length < dataStartIndex + lengthFieldSize)
                    throw new DeviceMessageValidationException(
                        ValidationErrorType.InsufficientDataLength,
                        "数据不足，无法读取状态值长度字段",
                        nameof(bytes),
                        $"至少需要 {dataStartIndex + lengthFieldSize} 字节",
                        $"{bytes.Length} 字节");

                valueLength = DeviceMessageUtilities.GetValueLength(valueType, bytes[dataStartIndex..]);
                dataStartIndex += lengthFieldSize;
            }
            else valueLength = DeviceMessageUtilities.GetValueLength(valueType, null);

            if (bytes.Length < dataStartIndex + valueLength)
                throw new DeviceMessageValidationException(
                    ValidationErrorType.InsufficientDataLength,
                    "数据不足，无法读取完整的状态值",
                    nameof(bytes),
                    $"状态值需要 {valueLength} 字节",
                    $"可用 {bytes.Length - dataStartIndex} 字节");

            var model = new DeviceMessageInfoReadingState
            {
                SID = sid,
                Type = (byte)valueType,
                Value = bytes.Slice(dataStartIndex, valueLength).ToArray()
            };
            Model = model;
            return model;
        }
    }
}
